import {designPage, reactive} from "plain-design-composition";
import {useTableOption} from "../../../module/useTableOption";
import {$configuration, $file, AutoTable, Button, Dropdown, DropdownOption, PlcImage, PlcInput, PlcOv, PlcTextarea} from "../../../../packages";
import {iOvMeta} from "../../../../packages/components/$ov/ov.utils";
import DownOutlined from "@ant-design/icons/DownOutlined";

export const demo1 = designPage(() => {

  const ov = $configuration.use('ov')!;

  const state = reactive({
    imgTypes: null as null | iOvMeta[]
  });

  ov.getOvByTypes('prod_img_type').then(val => state.imgTypes = val);

  const prodOption = useTableOption({
    // url: '/prod',
    url: 'http://1.116.13.72:7001/prod',
    showRows: 5,
    bodyRowHeight: 80,
  });

  const imgOption = useTableOption({
    url: '/upload',
    showRows: 5,
    bodyRowHeight: 80,
    parentOption: prodOption,
    parentMap: { headId: 'id' },
    permit: {
      show: {
        update: false,
        codes: {
          'inner-copy': false,
          'outer-insert': false,
        },
      }
    },
    buttons: [
      {
        label: '新建',
        code: 'upload',
        type: 'insert',
        seq: 0,
        position: 'outer',
        disabled: () => !prodOption.state.getTable()?.current.getNode()?.data,
        render: () => (
          <Dropdown
            key="upload"
            v-slots={{
              reference: () => (
                <Button loading={state.imgTypes == null} label="新建">
                  <span>新建</span>
                  <DownOutlined/>
                </Button>
              ),
              popper: () => <>
                {(state.imgTypes || []).map((i, index) => (
                  <DropdownOption key={index} label={i.name} onClick={() => newImageRecord(i.code)}/>
                ))}
              </>
            }}
          />
        )
      }
    ],
  });

  const newImageRecord = async (type: string) => {
    const imageFiles = await $file.chooseImage(true);
    const data = (await prodOption.methods.utils.getCurrentNode()).data;
    await new Promise<void>((resolve, reject) => {
      $file.upload({
        action: 'http://1.116.13.72:7001/saveFiles',
        file: imageFiles,
        filename: 'file',
        data: { headId: data.id, attr1: type },
        onSuccess: () => resolve(),
        onError: () => reject(),
      });
    });
    await imgOption.methods.pageMethods.reload();
  };

  return () => (
    <div>
      <AutoTable option={prodOption}>
        <PlcImage title="产品图片" field="imgPath" imgKeyField="imgId"/>
        <PlcInput title="产品名称" field="name" defaultSearch/>
        <PlcOv title="产品类型" field="type" ov="prod_type"/>
      </AutoTable>
      <AutoTable option={imgOption}>
        <PlcImage title="图片" field="path"/>
        <PlcTextarea title="地址" field="path"/>
        <PlcOv title="图片类型" field="attr1" ov="prod_img_type" defaultSearch/>
      </AutoTable>
    </div>
  );
});
